package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.UserRoleFrom;
import com.moss.cloud.base.biz.mapper.SysUserRoleMapper;
import com.moss.cloud.base.biz.service.ISysRoleService;
import com.moss.cloud.base.biz.service.ISysUserRoleService;
import com.moss.cloud.common.base.model.po.SysRole;
import com.moss.cloud.common.base.model.po.SysUserRole;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.constant.RoleCode;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.core.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色服务实现
 *
 * @author 瑾年
 * @date 2023年3月24日
 */
@Slf4j
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    private final ISysRoleService sysRoleService;

    public SysUserRoleServiceImpl(ISysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }

    /**
     * 批量保存用户角色
     *
     * @param userRoleFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveBatchUserRole(UserRoleFrom userRoleFrom) {
        List<SysUserRole> userRoles = this.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId,userRoleFrom.getUserId()));
        BooleanHandel.isTrue(CollectionUtils.isNotEmpty(userRoles)).trueHandle(()->{
            log.info("先将用户角色全部删除，再重新授权:{}",userRoleFrom.getUserId());
            this.remove(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId,userRoleFrom.getUserId()));
        });
        List<SysUserRole> sysUserRoles = CollectionUtils.isNotEmpty(userRoleFrom.getRoleIds()) ?
                userRoleFrom.getRoleIds().stream().map(item -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(item);
                    sysUserRole.setUserId(userRoleFrom.getUserId());
                    sysUserRole.setCreatedBy(UserContextHolder.getUsername());
                    sysUserRole.setCreatedTime(LocalDateTime.now());
                    return sysUserRole;
                }).collect(Collectors.toList()) : this.getDefaultUserRoles(userRoleFrom.getUserId());
        return this.saveBatch(sysUserRoles);
    }

    /**
     * 组装系统默认用户角色
     *
     * @param userId
     * @return
     */
    private List<SysUserRole> getDefaultUserRoles(Long userId) {
        return this.getDefaultRole().stream().map(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(item);
            sysUserRole.setUserId(userId);
            sysUserRole.setCreatedBy(UserContextHolder.getUsername());
            sysUserRole.setCreatedTime(LocalDateTime.now());
            return sysUserRole;
        }).collect(Collectors.toList());
    }

    /**
     * 获取系统默认角色
     *
     * @return
     */
    @Override
    public List<Long> getDefaultRole() {
        SysRole sysRole = sysRoleService.getSysRole(Constant.SYSTEM_DEF_ROLE);
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(sysRole.getId());
        return roleIds;
    }

    /**
     * 用户ID查询角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> roleInfoByUserId(Long userId) {
        List<SysUserRole> sysUserRoles = this.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userId));
        BooleanHandel.trueThrow(CollectionUtils.isEmpty(sysUserRoles)).throwMessage(SystemErrorType.DATE_EMPTY);
        List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        return this.sysRoleService.list(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, roleIds));
    }

    /**
     * 重置用户角色为普通用户
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetUserRole(Long userId){
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(RoleCode.USER_USER_ID);
        return this.save(sysUserRole);
    }
}
